package user

import (
	"blog/pkg/logger"
	"blog/pkg/model"
	"blog/pkg/password"
	"blog/pkg/types"
)

func (user *User) Create() (err error) {
	if err = model.DB.Create(&user).Error; err != nil {
		logger.LogError(err)
		return err
	}
	return nil
}

func Get(uid string) (User, error) {
	var _user User
	id := types.StringToUint64(uid)

	if err := model.DB.First(&_user, id).Error; err != nil {
		logger.LogError(err)
		return _user, err
	}
	return _user, nil
}

func GetByEmail(email string) (User, error) {

	var user User

	if err := model.DB.Where("email = ?", email).First(&user).Error; err != nil {
		return user, err
	}

	return user, nil
}

func (user *User) ComparePassword(_password string) bool {

	return password.CheckHash(_password, user.Password)
}

func All() ([]User, error) {
	var users []User
	if err := model.DB.Find(&users).Error; err != nil {
		return users, err
	}
	return users, nil
}
